import { ref } from "vue";
import Map from "@arcgis/core/Map";
import MapView from "@arcgis/core/views/MapView";
import TileLayer from "@arcgis/core/layers/TileLayer";
import Basemap from "@arcgis/core/Basemap";
import Graphic from "@arcgis/core/Graphic";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer";
import WMTSLayer from "@arcgis/core/layers/WMTSLayer";
import WebTileLayerProperties from "@arcgis/core/layers/WebTileLayer";
import WebTileLayer from "@arcgis/core/layers/WebTileLayer";
import Compass from "@arcgis/core/widgets/Compass";
import Sketch from "@arcgis/core/widgets/Sketch";
import TileInfo from "@arcgis/core/layers/support/TileInfo";
import PolygonSymbol3D from "@arcgis/core/symbols/PolygonSymbol3D";
import ExtrudeSymbol3DLayer from "@arcgis/core/symbols/ExtrudeSymbol3DLayer";
import SpatialReference from "@arcgis/core/geometry/SpatialReference";
import proj4 from "proj4";
import Extent from "@arcgis/core/geometry/Extent";
import Query from "@arcgis/core/rest/support/Query";
import BuildingSceneLayer from "@arcgis/core/layers/BuildingSceneLayer";
import FeatureLayer from "@arcgis/core/layers/FeatureLayer";
import SceneLayer from "@arcgis/core/layers/SceneLayer";
import MapImageLayer from "@arcgis/core/layers/MapImageLayer";
import SceneView from "@arcgis/core/views/SceneView";
import Point from "@arcgis/core/geometry/Point";
import TextSymbol from "@arcgis/core/symbols/TextSymbol";
import TextSymbol3DLayer from "@arcgis/core/symbols/TextSymbol3DLayer";
import PointSymbol3D from "@arcgis/core/symbols/PointSymbol3D";
import SimpleRenderer from "@arcgis/core/renderers/SimpleRenderer";
// import  Query  from "@arcgis/core/tasks/support/Query";
import * as query from "@arcgis/core/rest/query.js";
import SimpleLineSymbol from "@arcgis/core/symbols/SimpleLineSymbol";
import LabelSymbol3D from "@arcgis/core/symbols/LabelSymbol3D";
import Camera from "@arcgis/core/Camera";
import PictureMarkerSymbol from "@arcgis/core/symbols/PictureMarkerSymbol";
import { loadModules } from "esri-loader";
// import proj4 from 'proj4';
import { ElMessage } from "element-plus";
import zhgl_gx from "@/assets/image/underGround/zhgl_gx.png";
import pointPic from "@/assets/image/underGround/point.png";
import zhgl_length from "@/assets/image/underGround/zhgl_length.png";
import * as projection from "@arcgis/core/geometry/projection";
import subway from "@/assets/image/underGround/subway.png";
import gl from "@/assets/image/underGround/gl.png";
import sb from "@/assets/image/underGround/sb.png";
import pork from "@/assets/image/underGround/pork.png";
import project from "@/assets/image/underGround/project.png";
import warning from "@/assets/image/underGround/warning.png";
import jsonData from "./result1.json";
import sb_rain from "@/assets/image/underGround/sb_rain.png";
import sb_zd from "@/assets/image/underGround/sb_zd.png";
import sb_jll from "@/assets/image/underGround/sb_jll.png";
import sb_jg from "@/assets/image/underGround/sb_jg.png";
import sb_psg from "@/assets/image/underGround/sb_psg.png";
import API from "@/network/api";
import sb_yld from "@/assets/image/underGround/sb_yld.png";
import { useFields } from "./useFields";
import { useStore } from "vuex";
import { keysOf } from "element-plus/es/utils";
import { toMercator } from "@turf/turf";
import { color, number } from "echarts";
import { debounce, throttle } from "lodash";
import parking from "@/assets/image/label/font/parking.png";
import sb1 from "@/assets/image/label/glgx/sb1.png";
import sb2 from "@/assets/image/label/glgx/sb2.png";
import sb3 from "@/assets/image/label/glgx/sb3.png";
import sb4 from "@/assets/image/label/glgx/sb4.png";
import sb5 from "@/assets/image/label/glgx/sb5.png";

import front1 from "@/assets/image/label/font/font1.png";
import front2 from "@/assets/image/label/font/font2.png";
import front3 from "@/assets/image/label/font/font3.png";
import projet1 from "@/assets/image/label/project/projet1.png";
import projet2 from "@/assets/image/label/project/projet2.png";
import projet3 from "@/assets/image/label/project/projet3.png";
import projet4 from "@/assets/image/label/project/projet4.png";
import projet5 from "@/assets/image/label/project/projet5.png";
import projet6 from "@/assets/image/label/project/projet6.png";
import projet7 from "@/assets/image/label/project/projet7.png";
import projet8 from "@/assets/image/label/project/projet8.png";
import projet9 from "@/assets/image/label/project/projet9.png";
import yunx1 from "@/assets/image/label/yunx/yunxin1.png";
import yunx2 from "@/assets/image/label/yunx/yunxin2.png";
import yunx3 from "@/assets/image/label/yunx/yunxin3.png";
import yunx4 from "@/assets/image/label/yunx/yunxin4.png";
import yunx5 from "@/assets/image/label/yunx/yunxin5.png";
import yj1 from "@/assets/image/label/yj/yj1.png";
import yj2 from "@/assets/image/label/yj/yj2.png";
import yj3 from "@/assets/image/label/yj/yj3.png";
import yj4 from "@/assets/image/label/yj/yj4.png";
import yj5 from "@/assets/image/label/yj/yj5.png";
// import { mapTree } from "../../public/app/mapTree";
import axios from "axios";
import { useMap } from "@/hook/useMap";
const store = useStore();
let mapTree: any = [];
let apiMaparr: any = [];
let graphicsLayersList: any = [];
let glDevicelist: any = [];
let glhjlist: any = [];
let searchLayerVisibel: any;
let map: any;
let view: any;
let graphicsLayer: any = null;
let subWaylayer: any = null;
let PortgraphicsLayer: any = new GraphicsLayer();
let openPop = false;
const tileUrl = import.meta.env.VITE_APP_tileip;
// let projectInfo: Map = new Map();
var mapControlVisibleMap: Map = new Map();
var mapControOpacityMap: Map = new Map();
var apiMap: Map = new Map();
const underGroundFeature =
  tileUrl +
  "server/rest/services/Hosted/%E5%A2%A8%E6%B0%B4%E6%B9%96%E7%9A%84%E7%9F%A2%E9%87%8F%E7%AE%A1%E7%BA%BF%E7%AE%A1%E7%82%B9/FeatureServer ";
let scenceList = reactive([]);
const underGroundScenceList = reactive([
  {
    url: tileUrl + "server/rest/services/Hosted/A_BIM_HYQYSDW/SceneServer",
    name: "钟家村雨水井",
    layer: "",
  },
  {
    url: tileUrl + "server/rest/services/Hosted/A_BIM_HYQWSDW/SceneServer",
    name: "钟家村污水井",
    layer: "",
  },
  {
    url: tileUrl + "server/rest/services/Hosted/A_BIM_HYQYSGD01/SceneServer",
    name: "钟家村雨水管道模型1",
    layer: "",
  },
  {
    url: tileUrl + "server/rest/services/Hosted/A_BIM_HYQYSGD02/SceneServer",
    name: "钟家村雨水管道模型2",
    layer: "",
  },
  {
    url: tileUrl + "server/rest/services/Hosted/A_BIM_HYQYSGD03/SceneServer",
    name: "钟家村雨水管道模型3",
    layer: "",
  },
  {
    url: tileUrl + "server/rest/services/Hosted/A_BIM_HYQWSGD/SceneServer",
    name: "钟家村污水管道模型",
    layer: "",
  },
  {
    url: tileUrl + "server/rest/services/Hosted/A_BIM_GLMX/SceneServer",
    name: "琴台大道：",
    layer: "",
  },
]);
const HomeScenceList = reactive([
  // {
  //   url: tileUrl + "server/rest/services/Hosted/A_BIM_HYQYSDW/SceneServer",
  //   name: "钟家村雨水井",
  //   layer: "",
  // },
]);
const featureServer = reactive([
  {
    url: tileUrl + "server/rest/services/Hosted/A_XZQH_XJ_HYQ/FeatureServer/0",
    name: "汉阳区",
    layer: "",
  },
  {
    url:
      tileUrl + "server/rest/services/Hosted/A_XZQH_XJ_HYQJD1/FeatureServer/1",
    name: "街道",
    layer: "",
  },
  {
    url:
      tileUrl + "server/rest/services/Hosted/A_XZQH_CJ_CJXZQ/FeatureServer/33",
    name: "村级",
    layer: "",
  },
  {
    url: "https://hyportal.gis.cn/server/rest/services/Hosted/%E5%9C%B0%E9%93%81%E8%B7%AF%E7%BA%BF%E5%9B%BE/FeatureServer/0",
    name: "地铁线路",
    layer: "",
  },
  {
    url: " https://hyportal.gis.cn/server/rest/services/Hosted/道路路面/FeatureServer/2",
    name: "道路路面",
    layer: "",
  },
]);
let highGraphic: any = null;

export function useFunc() {
  // 自动滚动

  const autoScroll = (element: any, direction = "vertical") => {
    let isScroll = true;
    let scrollAmount = 0;
    const step = 2; // 每次滚动的像素数
    const delay = 100; // 滚动步进的时间间隔（毫秒）
    element.addEventListener("mouseover", () => {
      isScroll = false;
    });
    element.addEventListener("mouseout", () => {
      isScroll = true;
    });

    // 滚动函数
    const scroll = () => {
      if (direction === "vertical") {
        if (isScroll) {
          element.scrollTop += step;

          if (
            element.scrollTop + element.clientHeight >=
            element.scrollHeight
          ) {
            element.scrollTop = 0; // 重置滚动位置
          }
        }
      } else {
        // 'horizontal'
        if (isScroll) {
          element.scrollLeft += step;
          if (element.scrollLeft + element.clientWidth >= element.scrollWidth) {
            element.scrollLeft = 0; // 重置滚动位置
          }
        }
      }
      scrollAmount += step;
      setTimeout(scroll, delay);
    };

    // 开始滚动
    scroll();
  };

  const createMap = async (type: any) => {
    let scenceList: { url: string; name: string; layer: string }[] = [];
    scenceList = type == "underGround" ? underGroundScenceList : HomeScenceList;
    let basemap = new Basemap({
      baseLayers: [
        //遥感底图
        new TileLayer({
          url:
            tileUrl + "/server/rest/services/Hosted/A_WXYX_WHS_2022/MapServer", // 底图1服务地址
          title: "Basemap",
          visible: true,
        }),
        //正射底图
        new TileLayer({
          url: tileUrl + "/server/rest/services/Hosted/DOM20240315/MapServer", // 底图1服务地址
          title: "Basemap2",
          visible: false,
        }),
      ],
      title: "basemap",
      id: "basemap",
    });
    //底图
    map = new Map({
      basemap: basemap,
    });
    view = new SceneView({
      container: "viewDiv2",
      qualityProfile: "high",
      map: map,
      spatialReference: {
        wkid: 4547,
      },
      extent: new Extent({
        xmin: 515349.97919999994,
        ymin: 3374268.4757000003,
        xmax: 526836.0662000002,
        ymax: 3384917.1437,
        spatialReference: { wkid: 4547 },
      }),
    });
    view.ui.components = [];//清空所有ESRI自带的组件
    //区行政区划
    var qulayer = new FeatureLayer({
      url: featureServer[0].url,
      outFields: ["*"],
      renderer: {
        type: "simple",
        symbol: {
          type: "simple-line",
          color: "rgba(250, 135, 39, 1)",
          width: "12px", // 边框宽度
          outline: {
            // 边框样式
            color: "red", // 边框颜色
            width: "12px", // 边框宽度
          },
        },
      },
    });
    map.add(qulayer);

    //街道行政规划
    var jdlayer = new FeatureLayer({
      url: featureServer[1].url,
      outFields: ["*"],
      visible: false,
      renderer: {
        type: "simple", // autocasts as new SimpleRenderer()
        symbol: {
          type: "simple-fill", // autocasts as new SimpleFillSymbol()
          color: "rgba(3, 230, 254, 0.1)", // 填充颜色，使用 RGBA 格式
          outline: {
            // 边框样式
            color: "#55D2EF", // 边框颜色
            width: "2px", // 边框宽度
          },
        },
      },
    });
    map.add(jdlayer);

    if (type == "underGround") {
      //物探点
      const pictureSymbol = {
        type: "picture-marker", // autocasts as new PictureMarkerSymbol()
        url: pointPic, // 图片的 URL
        width: "32px",
        height: "32px",
      };
      var layerIds = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
      layerIds.forEach(function (id) {
        if (id <= 5) {
          var layer = new FeatureLayer({
            url: underGroundFeature + "/" + id,
            outFields: ["*"],
            renderer: {
              type: "simple",
              symbol: pictureSymbol,
            },
          });
          // map.add(layer);
        }
      });
    } else {
    }
    // scenceList.forEach((item: any) => {
    //   let layer = new BuildingSceneLayer({
    //     url: item.url,
    //     title: item.name,
    //     extent: new Extent({
    //       xmin: 515349.97919999994,
    //       ymin: 3374268.4757000003,
    //       xmax: 526836.0662000002,
    //       ymax: 3384917.1437,
    //       spatialReference: { wkid: 4547 },
    //     }),
    //   });
    //   item.layer = layer;
    //   // console.log(scenceList.value, "scenceList.value");

    //   map.layers.add(layer);
    // });

    view.watch("camera", function (camera: any) {});
    //  地图树
    var basemapLayer = map.basemap.baseLayers.items[0];
    var basemapLayer1 = map.basemap.baseLayers.items[1];

    mapControlVisibleMap.set("2", basemapLayer); //底图
    mapControlVisibleMap.set("3", jdlayer); //底图
    mapControlVisibleMap.set("4", qulayer); //底图
    mapControlVisibleMap.set("5", basemapLayer1); //底图
    // const mapTree:any = inject('maptreeData')

    if (type == "underGround") {
      let underGroundcommom = [
        {
          id: 47,
          label: "管廊",
          default: true,
          show: true,
          type: "folder",
          children: [
            {
              id: 48,
              label: "二维管廊",
              customAttributes: {
                api: "local",
                map: useMap().pipe2dMap,
              },
              url:
                tileUrl +
                // "/server/rest/services/Hosted/B_SZY_SXSW_HP/FeatureServer",
                "/server/rest/services/Hosted/A_BIM_GLMX_QTHX/FeatureServer/35",
              default: true,
              show: true,
              type: "layer",
              secondType: "polygon3d",
              color: "rgba(92, 2, 5, 1)",
              mapOb: "",
              children: [],
            },
            {
              id: 49,
              label: "三维管廊",

              type: "folder",
              children: [
                {
                  id: 50,
                  label: "琴台大道管廊",
                  customAttributes: {
                    api: "local",
                    map: useMap().glMap,
                  },
                  definitionExpression: "Fam_盖板 = '盖板",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/A_BIM_GLMX/SceneServer",
                  default: false,
                  show: false,
                  type: "layer",
                  secondType: "bim",
                  mapOb: "",
                  children: [],
                },
              ],
            },
          ],
        },
        {
          id: 51,
          label: "管线",
          default: true,
          show: true,
          type: "folder",
          children: [
            {
              id: 52,
              label: "二维管线",
              default: true,
              show: true,
              type: "folder",
              children: [
                ///////////////////
                {
                  id: 53,
                  label: "给水管线",
                  customAttributes: {
                 api: "local",
                map: useMap().pipeLineMap,
                  },
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/A_GXGL_JSGX/FeatureServer/0",
                  default: true,
                  show: true,
                  type: "layer",
                  secondType: "polyLine",
                  color: "rgba(68, 181, 246, 1)",
                  mapOb: "",
                  children: [],
                },
                {
                  id: 54,
                  label: "排水管线",
                  customAttributes: {
                    api: "local",
                   map: useMap().pipeLineMap,
                     },
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/A_GXGL_PSGX/FeatureServer/0",
                  default: true,
                  show: true,
                  type: "layer",
                  secondType: "polyLine",
                  color: "rgba(159, 159, 159, 1)",
                  mapOb: "",
                  children: [],
                },
                {
                  id: 55,
                  label: "电力管线",
                  customAttributes: {
                    api: "local",
                   map: useMap().pipeLineMap,
                     },
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/A_GXGL_DLGD/FeatureServer/0",
                  default: true,
                  show: true,
                  type: "layer",
                  secondType: "polyLine",
                  color: "rgba(247, 121, 99, 1)",
                  mapOb: "",
                  children: [],
                },
                {
                  id: 56,
                  label: "电信管线",
                  customAttributes: {
                    api: "local",
                   map: useMap().pipeLineMap,
                     },
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/A_GXGL_TXGD/FeatureServer/0",
                  default: true,
                  show: true,
                  type: "layer",
                  secondType: "polyLine",
                  color: "rgba(94, 235, 191, 1)",
                  mapOb: "",
                  children: [],
                },
                {
                  id: 57,
                  label: "燃气管线",
                  customAttributes: {
                    api: "local",
                   map: useMap().pipeLineMap,
                     },
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/A_GXGL_TRQGX/FeatureServer/0",
                  default: true,
                  show: true,
                  type: "layer",
                  secondType: "polyLine",
                  color: "rgba(247, 206, 101, 1)",
                  mapOb: "",
                  children: [],
                },
                {
                  id: 58,
                  label: "专用管线",
                  customAttributes: {
                  },
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/A_GXGL_PSGX/FeatureServer/0",
                  default: true,
                  show: true,
                  type: "layer",
                  secondType: "polyline",
                  color: "rgba(207, 110, 239, 1)",
                  mapOb: "",
                  children: [],
                },
                /////////////////////////
              ],
            },
            {
              id: 59,
              label: "三维管线",
              customAttributes: {
                api: "local",
                map: useMap().glMap,
              },
              url:
                tileUrl +
                "/server/rest/services/Hosted/A_BIM_HYQYSGD01/SceneServer",
              default: false,
              show: false,
              type: "layer",
              secondType: "bim",
              mapOb: "",
              children: [],
            },
          ],
        },
      ];
      mapTree = [
        {
          title: "驾驶舱",
          value: [
            {
              id: 46,
              label: "停车场",
              default: true,
              show: true,
              type: "folder",
              children: [
                {
                  id: 47,
                  label: "停车场",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/E_POI_HYQ_TCC/FeatureServer/8",
                  customAttributes: {
                    api: "local",
                    map: useMap().parking,
                  },
                  default: false,
                  show: false,
                  img: parking,
                  type: "layer",
                  secondType: "point",
                  children: [],
                  color: "rgba(92, 225, 255, 1)",
                  mapOb: "",
                },
              ],
            },
            ...underGroundcommom,
          ],
        },
        {
          title: "管廊管线",
          value: [
            ...underGroundcommom,
            {
              id: 60,
              label: "设备",
              default: true,
              show: true,
              type: "folder",
              children: [
                {
                  id: 61,
                  label: "点型光电感烟火灾探测器",
                  customAttributes: {
                    api: "/device/queryDeviceList",
                    url: import.meta.env.VITE_GL_URL,
                    map: useMap().glsbMap,
                    type:'压力传感器'
                  },

                  default: true,
                  show: true,
                  img: sb1,
                  type: "layer",
                  secondType: "GLpoint",
                  mapOb: "",
                  children: [],
                },
                {
                  id: 62,
                  label: "点型感温火灾探测器(A2R)",
                  customAttributes: {
                    api: "/device/queryDeviceList",
                    url: import.meta.env.VITE_GL_URL,
                    map: useMap().glsbMap,
                    type:'温火灾探测器'
                  },

                  default: true,
                  show: true,
                  img: sb2,
                  type: "layer",
                  secondType: "GLpoint",
                  mapOb: "",
                  children: [],
                },
                {
                  id: 63,
                  label: "火灾声光警报器",
                  customAttributes: {
                    api: "/device/queryDeviceList",
                    url: import.meta.env.VITE_GL_URL,
                    map: useMap().glsbMap,
                    type:'火灾声光警报器'
                  },

                  default: true,
                  show: true,
                  img: sb3,
                  type: "layer",
                  secondType: "GLpoint",
                  mapOb: "",
                  children: [],
                },
                {
                  id: 64,
                  label: "手动火灾警报器(电话)",
                  customAttributes: {
                    api: "/device/queryDeviceList",
                    url: import.meta.env.VITE_GL_URL,
                    map: useMap().glsbMap,
                    type:'流量计'
                  },

                  default: true,
                  show: true,
                  img: sb4,
                  type: "layer",
                  secondType: "GLpoint",
                  mapOb: "",
                  children: [],
                },
                {
                  id: 65,
                  label: "气体释放警报器",
                  customAttributes: {
                    api: "/device/queryDeviceList",
                    url: import.meta.env.VITE_GL_URL,
                    map: useMap().glsbMap,
                    type:'气体释放报警器'
                  },

                  default: true,
                  show: true,
                  img: sb5,
                  type: "layer",
                  secondType: "GLpoint",
                  mapOb: "",
                  children: [],
                },
                
              ],
            },
          ],
        },
      ];
    } else {
      mapTree = [
        {
          title: "驾驶舱",
          value: [
            {
              id: 6,
              label: "自然水系",
              default: true,
              show: true,
              type: "folder",
              children: [
                // {
                //   id:7,
                //   label: "干流",
                //   url:tileUrl + "/server/rest/services/Hosted/B_SZY_SXSW_HP/FeatureServer",
                //   default: true,
                //   show: true,
                //   type: "layer",
                //   children: [],
                //   mapOb: '',
                // },
                {
                  id: 8,
                  label: "湖泊",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/B_SZY_SXSW_HP/FeatureServer",
                  customAttributes: {
                    api: "/cockpit/getNaturalInfo",
                    type: "1",
                    map: useMap().huboMap,
                  },
                  default: true,
                  show: true,
                  type: "layer",
                  secondType: "polygon",
                  children: [],
                  color: "rgba(92, 225, 255, 1)",
                  mapOb: "",
                },
                {
                  id: 9,
                  label: "港渠",
                  default: true,
                  customAttributes: {
                    api: "/cockpit/getNaturalInfo",
                    type: "2",
                    map: useMap().huboMap,
                  },
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/%E6%B1%89%E9%98%B3%E5%8C%BA%E6%B0%B4%E6%B8%A0/FeatureServer",
                  show: true,
                  secondType: "polygon",
                  color: "rgba(3, 230, 254, 1)",
                  type: "layer",
                  children: [],
                  mapOb: "",
                },
              ],
            },
            {
              id: 10,
              label: "排水设施",
              default: true,
              show: true,
              type: "folder",
              children: [
                {
                  id: 11,
                  label: "泵站",
                  customAttributes: {
                    api: "/cockpit/getDrainageInfo",
                    type: "5",
                    map: useMap().bengzhanMap,
                  },
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/B_SZY_SLGC_HYQBZ/FeatureServer/0",
                  default: true,
                  show: true,
                  img: front1,
                  type: "layer",
                  secondType: "point",
                  mapOb: "",
                  children: [],
                },
                {
                  id: 12,
                  label: "提防",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/B_SZY_SLGC_YJDF/FeatureServer/11",
                  default: true,
                  customAttributes: {
                    api: "/cockpit/getDrainageInfo",
                    type: "7",
                    map: useMap().difangMap,
                  },
                  show: true,
                  type: "layer",
                  secondType: "point",
                  img: front2,
                  mapOb: "",
                  children: [],
                },
                {
                  id: 13,
                  label: "涵闸",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/B_SZY_SLGC_HYQHZ/FeatureServer/3",
                  default: true,
                  customAttributes: {
                    api: "/cockpit/getDrainageInfo",
                    type: "4",
                    map: useMap().hzMap,
                  },
                  show: true,
                  type: "layer",
                  secondType: "point",
                  img: front3,
                  mapOb: "",
                  children: [],
                },
              ],
            },
            {
              id: 14,
              label: "管网",
              default: true,
              show: true,
              type: "folder",
              children: [
                {
                  id: 15,
                  label: "排水管网",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/A_GXGL_PSGX/FeatureServer/0",
                  default: false,
                  customAttributes: {
                    api: "/cockpit/getDrainageInfo",
                    type: "6",
                    map: useMap().pipeMap,
                  },
                  show: false,
                  type: "layer",
                  secondType: "polyLine",
                  color: "rgba(3, 230, 254, 1)",
                  mapOb: "",
                  children: [],
                },
                {
                  id: 16,
                  label: "给水管网",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/A_GXGL_JSGX/FeatureServer/0",
                  default: false,
                  customAttributes: {
                    api: "/cockpit/getDrainageInfo",
                    type: "6",
                    map: useMap().pipeMap,
                  },
                  show: false,
                  type: "layer",
                  secondType: "polyLine",
                  color: "rgba(171,228,153, 1)",
                  mapOb: "",
                  children: [],
                },
              ],
            },
            {
              id: 42,
              label: "汇水分区",
              default: true,
              show: true,
              type: "folder",
              children: [
                {
                  id: 43,
                  label: "沿河抽排系统",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_HMCS_HSFQ/FeatureServer/8",
                  customAttributes: {
                    api: "/cockpit/getCatchmentInfo",
                    type: "",
                    map: useMap().hsMap,
                  },
                  definitionExpression: "type = '沿河抽排系统'",
                  default: false,
                  show: false,
                  type: "layer",
                  secondType: "polygon",
                  children: [],
                  color: "rgba(57, 134, 154, 1)",
                  mapOb: "",
                },
                {
                  id: 44,
                  label: "沿江抽排系统",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_HMCS_HSFQ/FeatureServer/8",
                  customAttributes: {
                    api: "/cockpit/getCatchmentInfo",
                    type: "",
                    map: useMap().hsMap,
                  },
                  definitionExpression: "type = '沿江抽排系统'",
                  default: false,
                  show: false,
                  type: "layer",
                  secondType: "polygon",
                  children: [],
                  color: "rgba(251, 203, 163, 1)",
                  mapOb: "",
                },
                {
                  id: 45,
                  label: "后官湖水系汇水区",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_HMCS_HSFQ/FeatureServer/8",
                  customAttributes: {
                    api: "/cockpit/getCatchmentInfo",
                    type: "",
                    map: useMap().hsMap,
                  },
                  definitionExpression: "type = '后官湖水系汇水区'",
                  default: false,
                  show: false,
                  type: "layer",
                  secondType: "polygon",
                  children: [],
                  color: "rgba(179, 248, 228, 1)",
                  mapOb: "",
                },
              ],
            },
          ],
        },
        {
          title: "建设管理",
          value: [
            {
              id: 17,
              label: "项目分类",
              default: true,
              show: true,
              type: "folder",
              children: [
                {
                  id: 18,
                  label: "污水收集完善",
                  default: true,
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_HMCS_XMD/FeatureServer/5",
                  customAttributes: {
                    api: "/build/getProjectInfo",
                    type: "",
                    map: useMap().projectMap,
                  },
                  definitionExpression: "type = '污水收集完善'",
                  show: true,
                  type: "layer",
                  secondType: "point",
                  img: projet7,
                  children: [],
                  mapOb: "",
                },
                {
                  id: 19,
                  label: "源头小区海绵建设",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_HMCS_XMD/FeatureServer/5",
                  customAttributes: {
                    api: "/build/getProjectInfo",
                    type: "",
                    map: useMap().projectMap,
                  },
                  definitionExpression: "type = '源头小区海绵建设'",
                  default: true,
                  show: true,
                  type: "layer",
                  secondType: "point",
                  img: projet6,
                  children: [],

                  mapOb: "",
                },
                {
                  id: 20,
                  label: "面源污染控制",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_HMCS_XMD/FeatureServer/5",
                  customAttributes: {
                    api: "/build/getProjectInfo",
                    type: "",
                    map: useMap().projectMap,
                  },
                  definitionExpression: "type = '面源污染控制'",
                  default: true,
                  show: true,
                  type: "layer",
                  secondType: "point",
                  img: projet5,
                  children: [],

                  mapOb: "",
                },
                {
                  id: 21,
                  label: "内涝治理及生态修复",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_HMCS_XMD/FeatureServer/5",
                  customAttributes: {
                    api: "/build/getProjectInfo",
                    type: "",
                    map: useMap().projectMap,
                  },
                  definitionExpression: "type = '内涝治理及生态修复'",
                  default: true,
                  show: true,
                  type: "layer",
                  img: projet4,
                  secondType: "point",
                  children: [],
                  mapOb: "",
                },
                {
                  id: 22,
                  label: "内涝放治",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_HMCS_XMD/FeatureServer/5",
                  customAttributes: {
                    api: "/build/getProjectInfo",
                    type: "",
                    map: useMap().projectMap,
                  },
                  definitionExpression: "type = '内涝放治'",
                  default: true,
                  show: true,
                  type: "layer",
                  img: projet3,
                  secondType: "point",
                  children: [],
                  mapOb: "",
                },
                {
                  id: 23,
                  label: "其他项目",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_HMCS_XMD/FeatureServer/5",
                  customAttributes: {
                    api: "/build/getProjectInfo",
                    type: "",
                    map: useMap().projectMap,
                  },
                  definitionExpression: "type = '其他项目'",
                  default: true,
                  show: true,
                  type: "layer",
                  img: projet1,
                  secondType: "point",
                  children: [],
                  mapOb: "",
                },
              ],
            },
            {
              id: 24,
              label: "污水处理厂",
              default: false,
              show: false,
              type: "folder",
              children: [
                {
                  id: 25,
                  label: "黄金口污水处理厂",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_HMCS_WSCLC/FeatureServer/0",
                  customAttributes: {
                    api: "/build/getSewageInfo",
                    map: useMap().wsMap,
                  },

                  default: false,
                  show: false,
                  type: "layer",
                  secondType: "polygon",
                  children: [],
                  color: "rgba(103, 20, 254, 1)",
                  mapOb: "",
                },
                {
                  id: 26,
                  label: "南太子湖污水处理厂",
                  default: false,
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_HMCS_WSCLC/FeatureServer/1",
                  show: false,
                  customAttributes: {
                    api: "/build/getSewageInfo",
                    map: useMap().wsMap,
                  },
                  secondType: "polygon",
                  color: "rgba(3, 230, 254, 1)",
                  type: "layer",
                  children: [],
                  mapOb: "",
                },
              ],
            },
            {
              id: 27,
              label: "积水点",
              default: false,
              show: false,
              type: "folder",
              children: [
                {
                  id: 28,
                  label: "积水点",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_HMCS_JSD/FeatureServer/6",
                  customAttributes: {
                    api: "/build/getPondingInfo",
                    type: "",
                    map: useMap().jsMap,
                  },
                  default: false,
                  show: false,
                  type: "layer",
                  secondType: "point",
                  img: projet9,
                  children: [],
                  mapOb: "",
                },
              ],
            },
          ],
        },
        {
          title: "运行检测及评价",
          value: [
            {
              id: 29,
              label: "物联设备",
              default: true,
              show: true,
              type: "folder",
              children: [
                {
                  id: 30,
                  label: "雨量检测仪",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/F_SBDW/FeatureServer/141",
                  customAttributes: {
                    api: "/build/getDeviceInfo",
                    type: "",
                    map: useMap().sbMap,
                  },
                  default: true,
                  show: true,
                  type: "layer",
                  definitionExpression: "type = '鹰眼摄像机'",
                  secondType: "point",
                  img: yunx5,
                  children: [],
                  mapOb: "",
                },
                {
                  id: 31,
                  label: "液位检测仪",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/F_SBDW/FeatureServer/141",

                  customAttributes: {
                    api: "/build/getDeviceInfo",
                    type: "",
                    map: useMap().sbMap,
                  },
                  default: true,
                  show: true,
                  type: "layer",
                  definitionExpression: "type = '积水液位监测'",
                  secondType: "point",
                  img: yunx4,
                  children: [],
                  mapOb: "",
                },
                {
                  id: 32,
                  label: "流量检测仪",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/F_SBDW/FeatureServer/141",

                  customAttributes: {
                    api: "/build/getDeviceInfo",
                    type: "",
                    map: useMap().sbMap,
                  },
                  default: true,
                  show: true,
                  definitionExpression: "type = '流量检测仪'",
                  type: "layer",
                  secondType: "point",
                  img: yunx3,
                  children: [],
                  mapOb: "",
                },
                {
                  id: 33,
                  label: "水质水位监测",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/F_SBDW/FeatureServer/141",

                  customAttributes: {
                    api: "/build/getDeviceInfo",
                    type: "",
                    map: useMap().sbMap,
                  },
                  default: true,
                  show: true,
                  definitionExpression: "type = '水质水位监测'",
                  type: "layer",
                  secondType: "point",
                  img: yunx2,
                  children: [],
                  mapOb: "",
                },
                {
                  id: 34,
                  label: "监控视频",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/F_SBDW/FeatureServer/141",

                  customAttributes: {
                    api: "/build/getDeviceInfo",
                    type: "",
                    map: useMap().sbMap,
                  },
                  default: true,
                  show: true,
                  definitionExpression:
                    "type = '渍水点摄像头' OR type = '人脸识别摄像机' OR type = '鹰眼摄像机' OR type = '险段摄像头' OR type = '内涝点摄像头' OR type = '涵闸摄像头'",
                  type: "layer",
                  secondType: "point",
                  img: yunx1,
                  children: [],
                  mapOb: "",
                },
              ],
            },
          ],
        },
        {
          title: "应急指挥",
          value: [
            {
              // id: 35,
              // label: "应急物资点",
              // url:tileUrl+"/server/rest/services/Hosted/G_YJ_YJWZCB/FeatureServer/16",
              // default: true,
              // show: true,
              // type: "layer",
              // secondType: "point",
              // img: yunx1,
              // children: [],
              // mapOb: "",
              id: 35,
              label: "应急物资",
              default: true,
              show: true,
              type: "folder",
              children: [
                {
                  id: 36,
                  label: "应急物资点",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_YJ_YJWZCB/FeatureServer/16",
                  customAttributes: {
                    api: "/build/getMaterialInfo",
                    type: "",
                    map: useMap().yjwzMap,
                  },
                  default: true,
                  show: true,
                  type: "layer",
                  secondType: "point",
                  img: yj5,
                  children: [],
                  mapOb: "",
                },
              ],
            },
            {
              id: 37,
              label: "应急避难场所",
              default: true,
              show: true,
              type: "folder",
              children: [
                {
                  id: 38,
                  label: "学校",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_YG_YJBNCS/FeatureServer/9",
                  // /cockpit/getSheltersInfo
                  customAttributes: {
                    api: "/cockpit/getSheltersInfo",
                    type: "",
                    map: useMap().sheltersMap,
                  },
                  default: true,
                  show: true,
                  type: "layer",
                  definitionExpression: "应急避难场所建设类型  = '学校类'",
                  secondType: "point",
                  img: yj1,
                  children: [],
                  mapOb: "",
                },
                {
                  id: 39,
                  label: "公园",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_YG_YJBNCS/FeatureServer/9",
                  customAttributes: {
                    api: "/cockpit/getSheltersInfo",
                    type: "",
                    map: useMap().sheltersMap,
                  },
                  default: true,
                  show: true,
                  type: "layer",
                  definitionExpression: "应急避难场所建设类型  = '公园类'",
                  secondType: "point",
                  img: yj2,
                  children: [],
                  mapOb: "",
                },
                {
                  id: 40,
                  label: "广场",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_YG_YJBNCS/FeatureServer/9",
                  customAttributes: {
                    api: "/cockpit/getSheltersInfo",
                    type: "",
                    map: useMap().sheltersMap,
                  },
                  default: true,
                  show: true,
                  type: "layer",
                  definitionExpression: "应急避难场所建设类型  = '广场类'",
                  secondType: "point",
                  img: yj3,
                  children: [],
                  mapOb: "",
                },
                {
                  id: 41,
                  label: "体育场",
                  url:
                    tileUrl +
                    "/server/rest/services/Hosted/G_YG_YJBNCS/FeatureServer/9",
                  customAttributes: {
                    api: "/cockpit/getSheltersInfo",
                    type: "",
                    map: useMap().sheltersMap,
                  },
                  default: true,
                  show: true,
                  type: "layer",
                  definitionExpression: "应急避难场所建设类型  = '体育场'",
                  secondType: "point",
                  img: yj4,
                  children: [],
                  mapOb: "",
                },
              ],
            },
          ],
        },
      ];
    }

    let common = {
      id: 1,
      label: "基础图层",
      default: true,
      show: true,
      type: "folder",
      children: [
        {
          id: 2,
          label: "卫星遥感影像",
          default: true,
          show: true,
          type: "basemap",
          opacity: 100,
          mapOb: basemap,
          children: [],
        },
        {
          id: 5,
          label: "正射影像",
          default: false,
          show: false,
          opacity: 100,
          type: "basemap",
          mapOb: basemap,
          children: [],
        },
        {
          id: 3,
          label: "街道行政区划",
          default: false,
          show: false,
          opacity: 100,
          type: "layer",
          mapOb: jdlayer,
          children: [],
        },
        {
          id: 4,
          label: "汉阳区行政区划",
          default: true,
          opacity: 100,
          show: true,
          type: "layer",
          mapOb: jdlayer,
          children: [],
        },
      ],
    };
    // /getSystemEnv.public"

    if(type== 'underGround'){
      let token=await getToken()
      let res=await getGLData('/device/queryDeviceList',{
        xt:'gl'
      })
      glDevicelist=res.data.data
      let gjlb= await getGLData('/jcyj/queryGjsjList',{
        xt:'gl'
      })
      glhjlist=gjlb.data.data
    }

    const addchild = (item: any, show: any) => {
      if (item.children.length > 0) {
        item.children.forEach((child: any) => {
          console.log(child, "addchild");

          // addPolygon(child,show);
          addchild(child, show);
        });
      } else {
        addPolygon(item, show);
      }
    };

    mapTree.forEach((item: any) => {
      if (item.value.length > 0) {
        item.value.forEach((i: any) => {
          let show = item.title == "驾驶舱" ? true : false;
          addchild(i, show);
          // if (i.children.length > 0) {
          //   i.children.forEach((child: any) => {
          //     console.log(child, "child");

          //     addPolygon(child, item.title == "驾驶舱" ? true : false);
          //   });
          // }
        });
      }
    });

    mapTree.map((item: any) => {
      item.value = [common, ...item.value];
    });
    for (let i = 0; i < 50; i++) {
      mapControOpacityMap.set(i.toString(), 100);
    }
    localStorage.setItem("mapTree", JSON.stringify(mapTree));
    popUp(view, "stateShow");
    moveOnTooltip(view);
  };
  const getGLData = async (url: any, params?: any) => {

    let token=localStorage.getItem("accessToken")
    const axiosInstance = axios.create({
      baseURL: "https://www.hycim.com/agcim-underground-rest",
      headers: {
        Authorization: `bearer ${token}`,
      },
    });
    const response: any = await axiosInstance.get(url,  {
      params: params
  });
    console.log(response, "GLpoint");
    return response;
  };

  const getToken=async()=>{
    const axiosInstance = axios.create({
      baseURL: "https://www.hycim.com/agcim-hy-index",
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      }
      // baseURL: "http://192.168.3.108/agcim-hy-index",
     
    });
    const response: any = await axiosInstance.post('/opu/om/users/queryLoginInfoByUserNameAndPassword',{

      userName:'TLCIM',
      password:'123456@2023'
     
    });
    let ob=response.data.content  
    const tokenaxiosInstance = axios.create({
      baseURL:"https://www.hycim.com/agcloud-sso",
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization':'Basic b3B1cy1hZG1pbjpvcHVzLWFkbWluMTIz'
      }
    });

    const tokenresponse: any = await tokenaxiosInstance.post('/authentication/form',{
    
      u:ob.userName,
      p:ob.password,
      proP:ob.proPassword,
      isApp:true,
      autoLogin:true
    });
   localStorage.setItem("accessToken",tokenresponse.data.content.access_token)  
    return response;

  }
  //  添加各种地图数据
  const addPolygon = async (item: any, show: any) => {
    if (apiMap.get(item.id.toString())) return;
    let ob: any;
    const highlightLayer = new GraphicsLayer();
    if (item.customAttributes)
      apiMap.set(item.id.toString(), item.customAttributes);
    apiMaparr.push({
      id: item.id.toString(),
      value: item.customAttributes,
    });
    console.log(apiMap, "apiMap");

    if (item.secondType == "polygon") {
      ob = new FeatureLayer({
        title: item.id,
        url: item.url,
        outFields: ["*"],
        definitionExpression: item.definitionExpression
          ? item.definitionExpression
          : "",

        visible: item.default && show,
        renderer: {
          type: "simple", // autocasts as new SimpleRenderer()
          symbol: {
            type: "simple-fill", // autocasts as new SimpleFillSymbol()
            color: item.color, // 填充颜色，使用 RGBA 格式
            outline: {
              // 边框样式
              color: "#55D2EF", // 边框颜色
              width: "2px", // 边框宽度
            },
          },
        },
      });
    } else if (item.secondType == "polygon3d") {
      console.log(item.id, "polygon3d");

      const polygonSymbol = new PolygonSymbol3D({
        symbolLayers: [
          new ExtrudeSymbol3DLayer({
            material: { color: "rgba(0, 0, 255, 0.6)" }, // 填充颜色
            size: 20, // 挤出高度
            edges: {
              type: "solid",
              color: "#55D2EF", // 边缘颜色
              size: 2, // 边缘宽度
            },
          }),
        ],
      });
      ob = new FeatureLayer({
        title: item.id, // 图层标题
        url: item.url, // 替换为你的 Feature Layer URL
        outFields: ["*"], // 获取所有字段
        visible: item.default && show, // 图层是否可见
        definitionExpression: "", // 可选：过滤表达式
        renderer: {
          type: "simple", // 简单渲染器
          symbol: polygonSymbol,
        },
      });
    } else if (item.secondType == "point") {
      const customIcon = new PictureMarkerSymbol({
        // url: entyImgMap.get(item.label), // 替换为你的自定义图标URL
        url: item.img,
        width: "124px",
        height: "124px",
      });
      const renderer = new SimpleRenderer({
        symbol: customIcon,
      });
      ob = new FeatureLayer({
        outFields: ["*"],
        title: item.id,
        definitionExpression: item.definitionExpression
          ? item.definitionExpression
          : "",

        url: item.url,
        renderer: renderer,
        visible: item.default && show,
      });
    } else if (item.secondType == "polyLine") {
      const customLineSymbol = new SimpleLineSymbol({
        color: rgbaStringToArray(item.color), // 线条颜色
        width: 2, // 线条宽度
      });

      // 创建渲染器
      const renderer = new SimpleRenderer({
        symbol: customLineSymbol,
      });

      // 创建 FeatureLayer 并应用渲染器
      ob = new FeatureLayer({
        outFields: ["*"],
        title: item.id,
        definitionExpression: item.definitionExpression
          ? item.definitionExpression
          : "",
        visible: item.default && show,
        url: item.url,

        renderer: renderer,
      });
    } else if (item.secondType == "bim") {
      ob = new BuildingSceneLayer({
        url: item.url,
        title: item.id,
        outFields: ["*"],
        visible: item.default && show,
        definitionExpression: item.definitionExpression
          ? item.definitionExpression
          : "",
        extent: new Extent({
          xmin: 515349.97919999994,
          ymin: 3374268.4757000003,
          xmax: 526836.0662000002,
          ymax: 3384917.1437,
          spatialReference: { wkid: 4547 },
        }),
      });
      // item.layer = layer;
      // console.log(scenceList.value, "scenceList.value");
      console.log(item.url, item.id, "nbim");

      // map.layers.add(layer);
    } else if (item.secondType == "GLpoint") {
      // getGLData(item.customAttributes.api,{
      //   xt:'gl'
      // }).then((response) => {
      //   let res = response.data.data;
      
      // });
      let res=glDevicelist.filter((i:any)=>i.sbmc==item.customAttributes.type);
      console.log(res, glDevicelist,"glDevicelist");
      
      if (res&&res.length > 0) {
        graphicsLayer = new GraphicsLayer({
          title: item.id,
          // visible: item.default && show,
          visible: item.default && show,
        });

        res.forEach((e: any) => {
          console.log(Number(e.zbX), Number(e.zbY), "GLpoint");

          const epsg4547Def =
            "+proj=tmerc +lat_0=0 +lon_0=114 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs";
          proj4.defs("EPSG:4547", epsg4547Def);
          // 示例坐标 WGS84
          const wgs84Coord = [Number(e.zbX), Number(e.zbY)];
          // 执行转换
          let point4547 = proj4("EPSG:4326", "EPSG:4547", wgs84Coord);
          // 打印转换后的坐标
          const originalPoint = new Point({
            x: point4547[0],
            y: point4547[1],
            spatialReference: { wkid: 4547 }, // 假设原始数据为WGS84坐标系
          });
          console.log(originalPoint, point4547[0], point4547[1], "point4547");

          const symbol = new PictureMarkerSymbol({
            url: item.img,
            width: "104px",
            height: "104px",
          });

          const graphic = new Graphic({
            geometry: originalPoint,
            symbol: symbol,
            title:e.sbbh,
            attributes: e,
          });
          console.log(graphic, "graphicgraphic");
          graphicsLayer.add(graphic);
          // })
        });
      }
      console.log(graphicsLayer, "graphicsLayer");
      graphicsLayersList.push(graphicsLayer);
      map.add(graphicsLayer);
      mapControlVisibleMap.set(item.id.toString(), graphicsLayer);
    }
    if (item.secondType != "GLpoint") {
      map.add(ob);
      mapControlVisibleMap.set(item.id.toString(), ob);
    }

    // map.add(highlightLayer);
  };

  // 根据主题名称获取数据树数据
  const getDataTreeDataByTitle = (
    title: any,
    data: Array<any>,
    time: string
  ) => {
    let result: any = data.find((item: any) => item.title === title);
    console.log(title, data, result, "getDataTreeDataByTitle");

    console.log();

    if (time != "init") {
      result.value.forEach((item: any) => {
        if (view) {
          hideAllLayers(view, item);
        }
      });
    } else {
    }

    return result ? result.value : undefined;
  };

  /**
   * 将 rgba 颜色字符串转换为数组格式
   * @param {string} rgbaString - 例如 "rgba(3, 230, 254, 0.1)"
   * @returns {number[]} - 例如 [3, 230, 254, 0.1]
   */
  const rgbaStringToArray = (rgbaString: any) => {
    // 使用正则表达式提取 rgba 值
    const rgbaRegex = /^rgba?\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)$/;
    const result = rgbaString.match(rgbaRegex);

    if (result) {
      // 将提取的值转换为数组格式
      return [
        parseInt(result[1], 10),
        parseInt(result[2], 10),
        parseInt(result[3], 10),
        parseFloat(result[4]),
      ];
    } else {
      throw new Error("Invalid rgba string format");
    }
  };
  const checkvisible = (node: any) => {
    if (node.children.length > 0) {
      node.children.forEach((child: any) => {
        checkvisible(child);
      });
    } else {
      changeVisible(node, node.default);
    }
  };
  // 添加点 废弃
  const addpoint = async (type: string) => {
    // projection.load().then(async () => {
    //   graphicsLayer = new GraphicsLayer();
    //   if (type === "underGround") {
    //     // PortgraphicsLayer = new GraphicsLayer();
    //     let arr = await API.map.ParkingList({
    //       pageNumber: 1,
    //       pageSize: 9999,
    //     });
    //     let parkingData = arr.data.list;
    //     parkingData.forEach((item: any, index: any) => {
    //       const originalPoint = new Point({
    //         x: item.location.x,
    //         y: item.location.y,
    //         spatialReference: { wkid: 4547 }, // 假设原始数据为WGS84坐标系
    //       });
    //       // // 定义目标坐标系（CGCS2000，WKID 4547）
    //       // const spatialReferenceCGCS2000 = new SpatialReference({ wkid: 4547 });
    //       // // 转换坐标
    //       // let projectedPoint = projection.project(originalPoint, spatialReferenceCGCS2000);
    //       // arr[index].location=projectedPoint
    //       const symbol = new PictureMarkerSymbol({
    //         url: entyImgMap.get(item.type),
    //         width: "104px",
    //         height: "104px",
    //       });
    //       const graphic = new Graphic({
    //         geometry: originalPoint,
    //         symbol: symbol,
    //         visible: type === "underGround" ? false : true,
    //         attributes: item,
    //         popupTemplate: {},
    //       });
    //       graphicsLayer.add(graphic);
    //     });
    //     // PortgraphicsLayer.visible=false
    //     // map.add(PortgraphicsLayer);
    //   }
    //   // 模拟数据
    //   const fakeData =
    //     type === "underGround"
    //       ? useFields().fakeData
    //       : useFields().fakeDataSoong;
    //   fakeData.forEach((item: any) => {
    //     const point = new Point({
    //       longitude: item.location.x,
    //       latitude: item.location.y,
    //       spatialReference: { wkid: 4547 },
    //     });
    //     const symbol = new PictureMarkerSymbol({
    //       url: entyImgMap.get(item.type),
    //       width: "104px",
    //       height: "104px",
    //     });
    //     const graphic = new Graphic({
    //       geometry: point,
    //       symbol: symbol,
    //       visible: type === "underGround" ? false : true,
    //       attributes: item,
    //       popupTemplate: {},
    //     });
    //     graphicsLayer.add(graphic);
    //   });
    //   map.add(graphicsLayer);
    //   view.popup.autoOpenEnabled = false;
    //   // leftDownAction(view, "stateShow");
    // });
  };
  //改变可见性
  const changeVisible = (node: any, show: Boolean) => {
    console.log(node, show, "changeVisible");
    switch (node.type) {
      case "basemap":
        let ob = (mapControlVisibleMap as any).get(node.id.toString());
        ob.visible = show;
        break;
      case "layer":
        let layer = (mapControlVisibleMap as any).get(node.id.toString());
        if (layer) {
          layer.visible = show;
        }
        break;
      default:
        break;
    }
  };

  // 隐藏所有的底图图层
  const hideAllLayers = (view: any, item: any) => {
    if (view.map.basemap) {
      view.map.basemap.baseLayers.forEach(
        (layer: any) => (layer.visible = false)
      );
      view.map.basemap.referenceLayers.forEach(
        (layer: any) => (layer.visible = false)
      );
    }

    // 隐藏所有的地图图层
    if (view.map.layers) {
      view.map.layers.forEach((layer: any) => (layer.visible = false));
    }
    setTimeout(() => {
      checkvisible(item);
    }, 500);

    // 隐藏所有的图形图层
    // graphicsLayer.graphics.forEach((graphic:any) => graphic.visible = false);
  };
  //id定位
  const locationByid = (id: string) => {
    let ob;
    ob = (mapControlVisibleMap as any).get(id.toString());
    console.log(ob.fullExtent, "dnujeineiujbf");
    let extent = { ...ob.fullExtent, height: 100 };
    if (ob.fullExtent) {
      // view.goTo(ob)
      view.goTo({
        target: ob.fullExtent,
        zoom: 13, // 设定适当的缩放级别
      });
    } else {
      console.log("Layer extent is not yet available.");
    }
  };

  const jumpDetail = (item: any, label: any) => {
    console.log(item, label, "item_jumpDetail");
    let data = findItemById(mapTree, label);
    //在maptree中找到id位item.id的数据
    // console.log(data, "data_jumpDetail");
    if(item.name=="南太子湖污水处理厂"){
    locateFeature(data, item.objectId, "single");
    }else{
    locateFeature(data, item.id, "single");

    }
    // console.log(searchLayerVisibel,'locateFeature');
  };

  const locateFeature = (data: any, objectId: number, time: any) => {
    // 查找图层
    searchLayerVisibel = false;
    // console.log(data, "data");
    //多图层
    if (data.children) {
      data.children.forEach((item: any) => {
        locateFeature(item, objectId, "multi");
      });
    }
    let featureLayer: any;
    const layer = map.layers.forEach((layer: any) => {
      if (layer.title && layer.title == data.id) {
        featureLayer = layer;
      }
    });

    if (!featureLayer || !featureLayer.visible) {
      console.log(featureLayer, featureLayer.visible, "featureLayervisible");

      debounce(ElMessage.error({ message: "请先打开图层" }), 1000);
    }
    // console.log(objectId, featureLayer, "sdsdsf");
    const query = new Query({
      where: "objectid = " + objectId, // 查询条件：id 为 1
      // where: `objectid = ${objectId} OR fid = ${objectId} OR id = ${objectId}`,
      outFields: ["*"], // 获取所有字段
      returnGeometry: true, // 返回几何信息
    });

    if (!featureLayer || !featureLayer?.visible) {
      return false;
    } else {
      featureLayer
        .queryFeatures(query)
        .then(showFindResult)
        .catch((err) => {
          console.error("objectid 查询失败， fid 查询", err);

          // 如果 objectid 查询失败，尝试使用 fid 或 id 查询
          let query1 = new Query({
            where: `fid = ${objectId}`, // 查询条件：检查 fid 或 id
            outFields: ["*"],
            returnGeometry: true, // 返回几何信息
          });

          // 再次执行查询
          featureLayer
            .queryFeatures(query1)
            .then(showFindResult)
            .catch((err) => {
              console.error("fid 查询失败， id 查询", err);

              // 如果 objectid 查询失败，尝试使用 fid 或 id 查询
              let query2 = new Query({
                where: `id = ${objectId}`, // 查询条件：检查 fid 或 id
                outFields: ["*"],
                returnGeometry: true, // 返回几何信息
              });

              // 再次执行查询
              featureLayer
                .queryFeatures(query2)
                .then(showFindResult)
                .catch(console.error("都没找到", err));
            });
        });
    }
    // 执行查询

    // 显示查询结果
    function showFindResult(result: any) {
      console.log(result,'showFindResult');
      
      searchLayerVisibel = true;

      // let id= createAttributes(result.features[0].attributes)
      let graphic = result.features[0];
      let geometry = result.features[0].geometry;
      console.log(result, "cilcgeometry");

      hightLight(graphic, geometry);
      view.goTo({
        target: geometry.extent?.center || geometry, // 使用几何的中心，如果没有extent则使用几何本身
        zoom: 15, // 调整缩放级别以适合您的需求
      });
      getmapData(
        graphic,
        apiMaparr.find((item: any) => item.id == result.features[0].layer.title)
          .value,
        "stateShow",
        result.features[0].attributes
      );
    }
  };
  const findItemById = (items: any[], label: string): any => {
    for (const item of items) {
      // 检查当前项是否匹配ID
      if (item.label === label) {
        return item;
      }
      // 如果当前项有子项，递归查找子项
      if (item.children) {
        const found = findItemById(item.children, label);
        if (found) {
          return found;
        }
      }
      // 如果是文件夹结构，则递归其值
      if (item.value) {
        const found = findItemById(item.value, label);
        if (found) {
          return found;
        }
      }
    }
    return null;
  };

  // 点击获取属性
  const highlightLayer = new GraphicsLayer();

  const highlightGraphicsMap = new Map();
  const popUp = (view: any, htmlId: any) => {
    // 创建一个高亮图层
    map.add(highlightLayer);

    view.on("click", function (event: any) {
      view.hitTest(event).then(function (response: any) {
        console.log(response, "response");

        if (response.results.length) {
          const graphic = response.results[0].graphic;
          let id = graphic.layer.title;
          const res: any = apiMap.get(id);
          const geometry = graphic.geometry;
          if (id != 30 && id != 31 && id != 32 && id != 33 && id != 34 && id != 61 && id != 62 && id != 63 && id != 64 && id != 65) {
            showPopUp(graphic, geometry, "stateShow", res, response);
          } else {
            showPopUp(graphic, geometry, "device", res, response);
          }
        //   if ([30, 31, 32, 33, 34].includes(id)) {
        //     showPopUp(graphic, geometry, "device", res, response);
        // } else if ([ 61, 62, 63, 64,65].includes(id)) {
        //     showPopUp(graphic, geometry, "device", res, response);
        // } else {
        //     showPopUp(graphic, geometry, "stateShow", res, response);
        // }
        }
      });
    });
  };
  //管廊设备定位弹窗
  const showPopUpGl=(item:any)=>{
   let graphic= findGraphicBybh(item.sbbh)
   let res=apiMap.get('61')
    getmapData(graphic, res, "device", graphic.attributes);
  }
  const showPopUp = (
    graphic: any,
    geometry: any,
    htmlId: any,
    res: any,
    response?: any
  ) => {
    if (graphic.layer.type != "building-scene") hightLight(graphic, geometry);
    // 聚焦视角到点击的要素中心
    // view.goTo({
    //   target: geometry.extent?.center || geometry, // 使用几何的中心，如果没有extent则使用几何本身
    //   zoom: 15, // 调整缩放级别以适合您的需求
    // });
    getmapData(graphic, res, htmlId, graphic.attributes, response);
  };

  const hightLight = (graphic: any, geometry: any) => {
    console.log(graphic, geometry, "hightLight");
    
    let symbol;
    ///////////////////高亮
    // 清除之前的高亮效果
    if (highlightLayer.graphics.length > 0) {
      highlightLayer.removeAll();
    }
    if (geometry.type === "polygon") {
      // 高亮填充和边框变亮
      symbol = {
        type: "simple-fill",
        color: [255, 255, 0, 0.5], // 更亮的黄色，带透明度
        outline: {
          color: [255, 255, 0], // 边框颜色
          width: 3, // 更宽的边框
        },
      };
    } else if (geometry.type === "point") {
      // 放大符号
      let rendererSymbol
      if(!graphic.symbol){  rendererSymbol = graphic.layer.renderer.symbol;}
      else{rendererSymbol=graphic.symbol;}

      symbol = rendererSymbol.clone();
      symbol.width = "150px"; // 比如 "150px"
      symbol.height = "150px"; // 比如 "150px"
      symbol.outline = {
        color: [0, 0, 255], // 蓝色
        width: 40, // 外边框宽度
      };
      // symbol = rendererSymbol;
    } else if (geometry.type === "polyline") {
      // 高亮线条颜色变亮
      symbol = {
        type: "simple-line",
        color: [255, 255, 0], // 更亮的黄色
        width: 6, // 更宽的线条
      };
    }
    highlightGraphicsMap.set(graphic.attributes.id + graphic.attributes.name, {
      symbol: graphic.symbol,
      layer: graphic.layer,
      graphic: graphic,
    });

    // 创建高亮图形
    const highlightGraphic = new Graphic({
      geometry: geometry,
      symbol: symbol,
    });

    // 将高亮图形添加到高亮图层
    highlightLayer.add(highlightGraphic);
  };
  const tabClick = (value: any) => {
    const contentDivs = document.querySelectorAll(".popInfo");
    const imageInfoDivs = document.querySelectorAll(".imageInfo");
    const yhlistDivs = document.querySelectorAll(".yhlist");
    const multiImageInfoDivs = document.querySelectorAll(".multiImageInfo");

    const divVisibleControl = (contentDivs: any, value: any, type: any) => {
      contentDivs.forEach((content: any) => {
        console.log(content.getAttribute("data-show"), "getAttribute");

        if (content.getAttribute("data-show") == value) {
          content.style.display = type; // 显示内容
        } else {
          content.style.display = "none"; // 隐藏内容
        }
      });
    };
    divVisibleControl(contentDivs, value, "flex");
    divVisibleControl(imageInfoDivs, value, "block");
    divVisibleControl(yhlistDivs, value, "flex");
    divVisibleControl(multiImageInfoDivs, value, "flex");
  };

  const getmapData = (
    graphic: any,
    res: any,
    htmlId: any,
    attributes: any,
    response?: any
  ) => {
    console.log(graphic, res, htmlId, attributes,response, "getmapData");
    
    if (htmlId == "device") {
      (document.getElementById as any)("left_bar").innerHTML =
        "基本信息";
      (document.getElementById as any)("left_bar").setAttribute(
        "data-show",
        "1"
      );
     
      (document.getElementById as any)("right_bar").setAttribute(
        "data-show",
        "2"
      );
    }

    console.log(graphic, res, htmlId, attributes, "mapping");
    const mapping = res.map;
    if (!res) return;
    const apiUrl = import.meta.env.VITE_SERVER_URL;
    if (res.api == "local") {
      const pickedFeature = graphic;
     Popupposition(pickedFeature, htmlId, view, response);
      //清空
      const titleElement: any = document.getElementById("title");
      const valueElement: any = document.querySelector(".pop_value");

      // 清空内容
      titleElement.innerHTML = ""; // 清空标题文本
      valueElement.innerHTML = ""; // 清空值内容

      var stateShowDiv = document.getElementById(htmlId); // 首先获取 'htmlId' 元素
      var contentDiv = (stateShowDiv as any).querySelector(".content");
      contentDiv.innerHTML = "";
      //设备特殊弹窗
      console.log(htmlId, "htmlId");
      let resData = pickedFeature.attributes;
      console.log(resData, "resDataresData");

      (document.getElementById as any)("title").innerHTML =
        resData.name || resData.objectid;
      for (let item of mapping) {
        if (
          item.type == "title" ||
          item.type == "location" ||
          item.type == "id"
        )
          continue;
        if (item.type == "text") {
          var propertyValue = resData[item.en];
          console.log(propertyValue, "propertyValue ");

          if (!propertyValue) continue;
          console.log(propertyValue, "propertyValue");

          var popInfoDiv = document.createElement("div");
          popInfoDiv.className = "popInfo";
          popInfoDiv.style.overflowX = "hidden";
          popInfoDiv.style.width = "100%";
          popInfoDiv.style.height = "50px";
          popInfoDiv.style.display = "flex";
          popInfoDiv.style.fontFamily = '"OPPOSans-Regular", sans-serif'; // 添加回退字体
          popInfoDiv.style.fontSize = "20px";
          popInfoDiv.style.lineHeight = "38px";
          popInfoDiv.style.color = "rgba(230, 253, 255, 1)";
          popInfoDiv.style.padding = "10px";
          // 创建并设置 pop_distribute 元素
          var distributeDiv = document.createElement("div");
          distributeDiv.className = "pop_distribute";
          distributeDiv.textContent = item.ch;
          popInfoDiv.style.paddingLeft = "20px";

          distributeDiv.style.width = "50%";
          // 创建并设置 pop_value 元素
          var valueDiv = document.createElement("div");
          valueDiv.className = "pop_value";
          valueDiv.textContent = propertyValue;
          valueDiv.style.width = "50%";

          // 将 distributeDiv 和 valueDiv 添加到 popInfoDiv
          popInfoDiv.appendChild(distributeDiv);
          popInfoDiv.appendChild(valueDiv);
          popInfoDiv.setAttribute("data-show", item.show);

          // 将 popInfoDiv 添加到 contentDiv
          contentDiv.appendChild(popInfoDiv);
        } else if (item.type == "video") {
          const imageDiv = document.createElement("div");
          imageDiv.className = "imageInfo";
          imageDiv.style.overflowX = "hidden";
          imageDiv.style.width = "100%";
          imageDiv.style.height = "auto";
          imageDiv.style.display = "flex";
          imageDiv.style.flexDirection = "column";
          imageDiv.style.alignItems = "center";
          imageDiv.style.padding = "10px";

          // 创建并设置 img 元素
          const imgElement = document.createElement("img");
          imgElement.src =
            "https://t10.baidu.com/it/u=3891219635,218071745&fm=30&app=106&f=JPEG?w=640&h=500&s=5BA13D6210A257A56D9E148C0100E0E3";
          // imgElement.alt = description;
          imgElement.style.width = "100%"; // 可以根据需求调整
          imgElement.style.height = "auto"; // 可以根据需求调整
          imgElement.style.borderRadius = "8px";
          imageDiv.appendChild(imgElement);
          imageDiv.setAttribute("data-show", item.show);

          contentDiv.appendChild(imageDiv);
        } else if (item.type == "list") {
          var propertyValue = resData[item.en];
          for (let i of propertyValue) {
            const imageDiv = document.createElement("div");
            imageDiv.style.display = "none";
            imageDiv.className = "multiImageInfo";
            imageDiv.style.overflowX = "hidden";
            imageDiv.style.width = "100%";
            imageDiv.style.height = "300px";
            imageDiv.style.padding = "10px";

            for (let e in i) {
              let chValue;
              let type;
              let enValue;
              useMap().yhMap.forEach((a) => {
                if (a.en == e)
                  (chValue = a.ch), (type = a.type), (enValue = a.en);
              });
              if (type == "text" && chValue) {
                var popInfoDiv = document.createElement("div");
                popInfoDiv.className = "yhlist";
                popInfoDiv.style.overflowX = "hidden";
                popInfoDiv.style.width = "100%";
                popInfoDiv.style.height = "auto";
                popInfoDiv.style.display = "flex";
                // popInfoDiv.style.display = "none";
                popInfoDiv.style.fontFamily = '"OPPOSans-Regular", sans-serif'; // 添加回退字体
                popInfoDiv.style.fontSize = "20px";
                popInfoDiv.style.lineHeight = "38px";
                popInfoDiv.style.color = "rgba(230, 253, 255, 1)";
                popInfoDiv.style.padding = "10px";
                // 创建并设置 pop_distribute 元素
                var distributeDiv = document.createElement("div");
                distributeDiv.className = "pop_distribute";
                distributeDiv.textContent = chValue || "没找到";
                popInfoDiv.style.paddingLeft = "20px";

                distributeDiv.style.width = "50%";
                // 创建并设置 pop_value 元素
                var valueDiv = document.createElement("div");
                valueDiv.className = "pop_value";
                valueDiv.textContent = i[e];
                valueDiv.style.width = "50%";

                // 将 distributeDiv 和 valueDiv 添加到 popInfoDiv
                popInfoDiv.appendChild(distributeDiv);
                popInfoDiv.appendChild(valueDiv);
                popInfoDiv.setAttribute("data-show", item.show);
                contentDiv.appendChild(popInfoDiv);
              }
            }
          }
        }
      }
      return;
    }
    //管廊设备
    const pickedFeature = graphic;

    let type = graphic.layer.type;
    if(type == "graphics") {
      console.log("graphics", pickedFeature, htmlId, view);
      
      if (pickedFeature) {
        // 调用自定义的弹窗定位函数（需要另外实现）
        Popupposition(pickedFeature, htmlId, view);
        (document.getElementById as any)("right_bar").innerHTML =
        "告警信息";
        let attributes = pickedFeature.attributes;
        var stateShowDiv = document.getElementById("device"); // 首先获取 'stateShow' 元素
        var contentDiv = (stateShowDiv as any).querySelector(".content");
        contentDiv.innerHTML = "";
        (document.getElementById as any)("title").innerHTML =
          attributes.name;
    
        for (let key in attributes) {
          if (key == "title" || key == "location" || key == "id")
            continue;
          var propertyValue = attributes[key];
          let ob=mapping.find((i: any) => i.en == key)

          if (!propertyValue ||!ob) continue;
          console.log(propertyValue, "propertyValue");

          var popInfoDiv = document.createElement("div");
          popInfoDiv.className = "popInfo";
          popInfoDiv.style.overflowX = "hidden";
          popInfoDiv.style.width = "100%";
          popInfoDiv.style.height = "40px";
          popInfoDiv.style.display = "flex";
          popInfoDiv.style.fontFamily = '"OPPOSans-Regular", sans-serif'; // 添加回退字体
          popInfoDiv.style.fontSize = "20px";
          popInfoDiv.style.lineHeight = "38px";
          popInfoDiv.style.color = "rgba(230, 253, 255, 1)";
          popInfoDiv.style.padding = "10px";
          // 创建并设置 pop_distribute 元素
          var distributeDiv = document.createElement("div");
          distributeDiv.className = "pop_distribute";
          distributeDiv.textContent =  ob?ob.ch: "没找到";
          ;

          distributeDiv.style.width = "50%";
          // 创建并设置 pop_value 元素
          var valueDiv = document.createElement("div");
          valueDiv.className = "pop_value";
          valueDiv.textContent = propertyValue;
          valueDiv.style.width = "50%";
          popInfoDiv.setAttribute("data-show", "1");

          // 将 distributeDiv 和 valueDiv 添加到 popInfoDiv
          popInfoDiv.appendChild(distributeDiv);
          popInfoDiv.appendChild(valueDiv);

          // 将 popInfoDiv 添加到 contentDiv
          contentDiv.appendChild(popInfoDiv);
        }
        let list = glhjlist.filter((i: any) => i.sbmc == attributes.sbmc);
        console.log(glhjlist,list,attributes.sbmc,'gliset');
        if(list.length>0){
          for (let i of list){
   
            for (let e in i) {
              let chValue;
              let type;
              let enValue;
              useMap().glgjmap.forEach((a) => {
                if (a.en == e)
                  (chValue = a.ch), (type = a.type), (enValue = a.en);
              });
              if (type == "text" && chValue) {
                var popInfoDiv = document.createElement("div");
                popInfoDiv.className = "yhlist";
                popInfoDiv.style.overflowX = "hidden";
                popInfoDiv.style.width = "100%";
                popInfoDiv.style.height = "auto";
                // popInfoDiv.style.display = "flex";
                popInfoDiv.style.display = "none";
                popInfoDiv.style.fontFamily =
                  '"OPPOSans-Regular", sans-serif'; // 添加回退字体
                popInfoDiv.style.fontSize = "20px";
                popInfoDiv.style.lineHeight = "38px";
                popInfoDiv.style.color = "rgba(230, 253, 255, 1)";
                popInfoDiv.style.padding = "10px";
                // 创建并设置 pop_distribute 元素
                var distributeDiv = document.createElement("div");
                distributeDiv.className = "pop_distribute";
                distributeDiv.textContent = chValue || "没找到";
                popInfoDiv.style.paddingLeft = "20px";

                distributeDiv.style.width = "50%";
                // 创建并设置 pop_value 元素
                var valueDiv = document.createElement("div");
                valueDiv.className = "pop_value";
                valueDiv.textContent = i[e];
                valueDiv.style.width = "50%";

                // 将 distributeDiv 和 valueDiv 添加到 popInfoDiv
                popInfoDiv.appendChild(distributeDiv);
                popInfoDiv.appendChild(valueDiv);
                popInfoDiv.setAttribute("data-show", '2');
                contentDiv.appendChild(popInfoDiv);
              } 
            }
            hxDIV(contentDiv);

          }

        }
        // 更新 DOM 元素
        // updateDOM(attributes);
      }
    }else{axios
      .get(apiUrl + res.api, {
        params: {
          type: res.type,
          name: attributes.name ? attributes.name : "",
          id: createAttributes(attributes),
        },
      })
      .then((red: any) => {
        let resData = [];
        resData = red.data.data[0];
        // 处理响应数据
        // console.log("mapping+res", resData);
        const pickedFeature = graphic;

        if (type === "building-scene") {
        }
        else {
          if (pickedFeature) {
            // 调用自定义的弹窗定位函数（需要另外实现）
            Popupposition(pickedFeature, htmlId, view);
            //清空
            const titleElement: any = document.getElementById("title");
            const valueElement: any = document.querySelector(".pop_value");

            // 清空内容
            titleElement.innerHTML = ""; // 清空标题文本
            valueElement.innerHTML = ""; // 清空值内容

            var stateShowDiv:any = document.getElementById(htmlId); // 首先获取 'htmlId' 元素
            var contentDiv = (stateShowDiv as any).querySelector(".content");
            if(res.api=='/build/getPondingInfo'){
              stateShowDiv.style.width='700px'
            }else{
              stateShowDiv.style.width='500px'

            }
            contentDiv.innerHTML = "";
            //设备特殊弹窗
            console.log(htmlId, "htmlId");
            (document.getElementById as any)("right_bar").innerHTML =
            "隐患列表";
            (document.getElementById as any)("title").innerHTML = resData.name;
            const imageDiv = document.createElement("div");
            imageDiv.style.display = "flex";
            imageDiv.className = "multiImageInfo";
            imageDiv.style.overflowX = "hidden";
            imageDiv.style.width = "100%";
            imageDiv.style.height = "300px";
            imageDiv.style.padding = "10px";
            
            for (let item of mapping) {
              if (
                item.type == "title" ||
                item.type == "location" ||
                item.type == "id"
              )
                continue;
              if (item.type == "text") {
                var propertyValue = resData[item.en];
                console.log(propertyValue, "propertyValue ");

                if (!propertyValue) continue;
                console.log(propertyValue, "propertyValue");

                var popInfoDiv = document.createElement("div");
                popInfoDiv.className = "popInfo";
                popInfoDiv.style.overflowX = "hidden";
                popInfoDiv.style.width = "100%";
                popInfoDiv.style.height = "50px";
                popInfoDiv.style.display = "flex";
                popInfoDiv.style.fontFamily = '"OPPOSans-Regular", sans-serif'; // 添加回退字体
                popInfoDiv.style.fontSize = "20px";
                popInfoDiv.style.lineHeight = "38px";
                popInfoDiv.style.color = "rgba(230, 253, 255, 1)";
                popInfoDiv.style.padding = "10px";
                // 创建并设置 pop_distribute 元素
                var distributeDiv = document.createElement("div");
                distributeDiv.className = "pop_distribute";
                distributeDiv.textContent = item.ch;
                popInfoDiv.style.paddingLeft = "20px";

                distributeDiv.style.width = "50%";
                // 创建并设置 pop_value 元素
                var valueDiv = document.createElement("div");
                valueDiv.className = "pop_value";
                valueDiv.textContent = propertyValue;
                valueDiv.style.width = "50%";

                // 将 distributeDiv 和 valueDiv 添加到 popInfoDiv
                popInfoDiv.appendChild(distributeDiv);
                popInfoDiv.appendChild(valueDiv);
                popInfoDiv.setAttribute("data-show", item.show);

                // 将 popInfoDiv 添加到 contentDiv
                contentDiv.appendChild(popInfoDiv);
              } else if (item.type == "video") {
                const imageDiv = document.createElement("div");
                imageDiv.className = "imageInfo";
                imageDiv.style.overflowX = "hidden";
                imageDiv.style.width = "100%";
                imageDiv.style.height = "auto";
                imageDiv.style.display = "flex";
                imageDiv.style.flexDirection = "column";
                imageDiv.style.alignItems = "center";
                imageDiv.style.padding = "10px";

                // 创建并设置 img 元素
                const imgElement = document.createElement("img");
                imgElement.src =
                  "https://t10.baidu.com/it/u=3891219635,218071745&fm=30&app=106&f=JPEG?w=640&h=500&s=5BA13D6210A257A56D9E148C0100E0E3";
                // imgElement.alt = description;
                imgElement.style.width = "100%"; // 可以根据需求调整
                imgElement.style.height = "auto"; // 可以根据需求调整
                imgElement.style.borderRadius = "8px";
                imageDiv.appendChild(imgElement);
                imageDiv.setAttribute("data-show", item.show);

                contentDiv.appendChild(imageDiv);
              }else if (item.type == "multi_image") {
                 
                const imgBOXElement = document.createElement("div");
                const imgTitle = document.createElement("div");
                imgTitle.className = "pop_imgTitle";
                imgTitle.style.fontFamily =
                  '"OPPOSans-Regular", sans-serif'; // 添加回退字体
                imgTitle.style.fontSize = "20px";
                imgTitle.style.lineHeight = "38px";
                imgTitle.style.padding = "10px";
                if (item.en == "afterHandleImage") {
                  imgTitle.style.color = "#5CE1FF";
                  imgTitle.textContent = "◇处理后照片";
                  imgBOXElement.appendChild(imgTitle);
                }
                if (item.en == "handleImage") {
                  imgTitle.style.color = " #5CE1FF";
                  imgTitle.textContent = "◇处理中照片";
                  imgBOXElement.appendChild(imgTitle);
                }
                if (item.en == "beforeHandleImage") {
                  imgTitle.style.color = " #B8EB8F";
                  imgTitle.textContent = "◇处理前照片";
                  imgBOXElement.appendChild(imgTitle);
                }
                imgBOXElement.style.width = "200px"; // 可以根据需求调整
                imgBOXElement.style.height = "120px"; // 可以根据需求调整
                imgBOXElement.style.marginLeft = "20px"; // 可以根据需求调整
                // 创建并设置 img 元素
                const imgElement = document.createElement("img");
                imgElement.src = resData[item.en];
                // imgElement.alt = description;
                imgElement.style.width = "200px"; // 可以根据需求调整
                imgElement.style.height = "140px"; // 可以根据需求调整
                imgElement.style.marginLeft = "10px"; // 可以根据需求调整
                imgElement.style.borderRadius = "8px";
                imgBOXElement.appendChild(imgElement);
                imageDiv.appendChild(imgBOXElement);
                imageDiv.setAttribute("data-show", item.show);

                contentDiv.appendChild(imageDiv);
              } 
              else if (item.type == "list") {
                var propertyValue = resData[item.en];
                for (let i of propertyValue) {
                  const imageDiv = document.createElement("div");
                  imageDiv.style.display = "none";
                  imageDiv.className = "multiImageInfo";
                  imageDiv.style.overflowX = "hidden";
                  imageDiv.style.width = "100%";
                  imageDiv.style.height = "300px";
                  imageDiv.style.padding = "10px";

                  for (let e in i) {
                    let chValue;
                    let type;
                    let enValue;
                    useMap().yhMap.forEach((a) => {
                      if (a.en == e)
                        (chValue = a.ch), (type = a.type), (enValue = a.en);
                    });
                    if (type == "text" && chValue) {
                      var popInfoDiv = document.createElement("div");
                      popInfoDiv.className = "yhlist";
                      popInfoDiv.style.overflowX = "hidden";
                      popInfoDiv.style.width = "100%";
                      popInfoDiv.style.height = "auto";
                      // popInfoDiv.style.display = "flex";
                      popInfoDiv.style.display = "none";
                      popInfoDiv.style.fontFamily =
                        '"OPPOSans-Regular", sans-serif'; // 添加回退字体
                      popInfoDiv.style.fontSize = "20px";
                      popInfoDiv.style.lineHeight = "38px";
                      popInfoDiv.style.color = "rgba(230, 253, 255, 1)";
                      popInfoDiv.style.padding = "10px";
                      // 创建并设置 pop_distribute 元素
                      var distributeDiv = document.createElement("div");
                      distributeDiv.className = "pop_distribute";
                      distributeDiv.textContent = chValue || "没找到";
                      popInfoDiv.style.paddingLeft = "20px";

                      distributeDiv.style.width = "50%";
                      // 创建并设置 pop_value 元素
                      var valueDiv = document.createElement("div");
                      valueDiv.className = "pop_value";
                      valueDiv.textContent = i[e];
                      valueDiv.style.width = "50%";

                      // 将 distributeDiv 和 valueDiv 添加到 popInfoDiv
                      popInfoDiv.appendChild(distributeDiv);
                      popInfoDiv.appendChild(valueDiv);
                      popInfoDiv.setAttribute("data-show", item.show);
                      contentDiv.appendChild(popInfoDiv);
                    } else if (type == "multi_image") {
                      const imgBOXElement = document.createElement("div");
                      const imgTitle = document.createElement("div");
                      imgTitle.className = "pop_imgTitle";
                      imgTitle.style.fontFamily =
                        '"OPPOSans-Regular", sans-serif'; // 添加回退字体
                      imgTitle.style.fontSize = "20px";
                      imgTitle.style.lineHeight = "38px";
                      imgTitle.style.padding = "10px";
                      if (enValue == "afterHandleImage") {
                        imgTitle.style.color = "#5CE1FF";
                        imgTitle.textContent = "处理后照片";
                        imgBOXElement.appendChild(imgTitle);
                      }
                      if (enValue == "beforeHandleImage") {
                        imgTitle.style.color = " #FCE2B9";
                        imgTitle.textContent = "处理前照片";
                        imgBOXElement.appendChild(imgTitle);
                      }
                      imgBOXElement.style.width = "200px"; // 可以根据需求调整
                      imgBOXElement.style.height = "120px"; // 可以根据需求调整
                      // 创建并设置 img 元素
                      const imgElement = document.createElement("img");
                      imgElement.src = i[e];
                      // imgElement.alt = description;
                      imgElement.style.width = "200px"; // 可以根据需求调整
                      imgElement.style.height = "140px"; // 可以根据需求调整
                      imgElement.style.marginLeft = "10px"; // 可以根据需求调整
                      imgElement.style.borderRadius = "8px";
                      imgBOXElement.appendChild(imgElement);
                      imageDiv.appendChild(imgBOXElement);
                      imageDiv.setAttribute("data-show", item.show);

                      contentDiv.appendChild(imageDiv);
                    }
                  }
                  hxDIV(contentDiv);
                }

              }
            }
            // 更新 DOM 元素
            // updateDOM(attributes);
          }
        }
      })
      .catch((error) => {});
    }
  };
  //移动显示名称
  const createAttributes = (input: any) => {
    console.log(input, "createAttributes");
    
    let attributes: any = {};
    if ("objectid" in input) {
      attributes.id = input.objectid;
    } else if ("id" in input) {
      attributes.id = input.id;
    } else if ("fid" in input) {
      attributes.id = input.fid;
    // }else if(input.name=='黄金口污水处理厂'||input.name=='南太子湖污水处理厂'){
    //   attributes.id = null

    }
    return attributes.id;
  };
  const hxDIV=(contentDiv:any)=>{
    const hrElement = document.createElement("hr");
    hrElement.style.border = "1px solid #ccc"; // 可以根据需求调整样式
    hrElement.style.width = "100%";
    hrElement.style.margin = "10px 0"; // 根据需要调整
    hrElement.style.display = "none";
    hrElement.setAttribute("data-show", '2');
    contentDiv.appendChild(hrElement);
  }
  const moveOnTooltip = (view: any) => {
    const tooltip = document.createElement("div");
    tooltip.style.position = "absolute";
    tooltip.style.backgroundColor = "white";
    tooltip.style.border = "1px solid black";
    tooltip.style.padding = "5px";
    tooltip.style.display = "none";
    document.body.appendChild(tooltip);
    let hideTooltipTimeout: any = null;

    view.on("pointer-move", function (event: any) {
      // 执行 hitTest 检测
      view.hitTest(event).then(function (response: any) {
        const epsg4547Def =
          "+proj=tmerc +lat_0=0 +lon_0=114 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs";
        proj4.defs("EPSG:4547", epsg4547Def);
        // 示例坐标 WGS84
        const wgs84Coord = [
          response.ground.mapPoint.x,
          response.ground.mapPoint.y,
        ];
        // 执行转换
        let point4547 = proj4("EPSG:4547", "EPSG:4326", wgs84Coord);

        const results = response.results;

        if (results.length > 0) {
          const graphic = results[0].graphic;

          // const modelName =
          //   (graphic.attributes && graphic.attributes.name) ||
          //   graphic.attributes?.park_name; // 假设属性字段为 'name'
            const modelName =(graphic.attributes && graphic.attributes.name) || graphic.attributes?.park_name;
          // 显示工具提示
          if (modelName) {
            // console.log( event,' event');

            tooltip.innerText = modelName;
            tooltip.style.left = event.x + "px";
            // tooltip.style.top = event.y + "px";
            tooltip.style.top = event.y + "px";

            tooltip.style.fontSize = "26px"; // 修改字体大小
            tooltip.style.display = "block";
            tooltip.style.whiteSpace = "nowrap"; // 文字横向排列
            tooltip.style.background = "rgb(26, 54, 65)"; // 文字横向排列
            tooltip.style.color = "#fff"; // 文字横向排列

            // 如果有定时器，清除它
            if (hideTooltipTimeout) {
              clearTimeout(hideTooltipTimeout);
              hideTooltipTimeout = null;
            }
          } else {
            // 如果没有 modelName，将浮窗隐藏
            tooltip.style.display = "none";
          }
        } else {
          // 如果没有检测到结果，将浮窗隐藏
          // tooltip.style.display = "none";
        }
      });
    });

    // `pointer-leave` 事件监听器
    view.on("pointer-leave", function () {
      // 设置定时器，在两秒后隐藏浮窗
      tooltip.style.display = "none";
      // hideTooltipTimeout = setTimeout(() => {
      //   tooltip.style.display = "none";
      //   console.log('清除');
        
      // }, 100);
    });
  };

  const Popupposition = async (
    pickedFeature: any,
    htmlId: any,
    view: any,
    response?: any
  ) => {
    const [Point, SpatialReference, projection] = await loadModules([
      "esri/geometry/Point",
      "esri/geometry/SpatialReference",
      "esri/geometry/projection",
    ]);
    (document.getElementById as any)(htmlId).style.display = "none";
    console.log(pickedFeature, "pickedFeature");
    let x;
    let y;
    let point4547: any;
    let windowPosition: any;
    if (pickedFeature.geometry) {
      if (pickedFeature.geometry.type == "point") {
        x = pickedFeature.geometry.x;
        y = pickedFeature.geometry.y;
      } else if (pickedFeature.geometry.type == "polygon") {
        x = pickedFeature.geometry.centroid.x;
        y = pickedFeature.geometry.centroid.y;
      } else if (pickedFeature.geometry.type == "polyline") {
        x = pickedFeature.geometry.extent.center.x;
        y = pickedFeature.geometry.extent.center.y;
      }
      point4547 = new Point({
        x: x,
        y: y,
        spatialReference: new SpatialReference({ wkid: 4547 }),
      });
      windowPosition = view.toScreen(point4547);
    } else {
      windowPosition = response.screenPoint;
      console.log("windowPosition-response", response);
    }

    (document.getElementById as any)(htmlId).style.left =
      windowPosition.x + 150 + "px";
    (document.getElementById as any)(htmlId).style.top =
      windowPosition.y - 220 + "px";
    (document.getElementById as any)(htmlId).style.display = "block"; //弹出信息框
    if (pickedFeature.geometry) {
      view.watch("camera", function (camera: any) {
        var windowPosition = view.toScreen(point4547);
        (document.getElementById as any)(htmlId).style.left =
          windowPosition.x + 150 + "px";
        (document.getElementById as any)(htmlId).style.top =
          windowPosition.y - 220 + "px";
      });
    }
  };
  const flyByXY = (x: any, y: any) => {
    const point4547 = new Point({
      x: x,
      y: y,
      spatialReference: { wkid: 4547 }, // EPSG:4547
    });

    view.goTo({
      target: point4547, // 使用几何的中心，如果没有extent则使用几何本身
      zoom: 15, // 调整缩放级别以适合您的需求
    });
  };
  const flyByXY4326 = (x: any, y: any) => {
    const epsg4547Def =
      "+proj=tmerc +lat_0=0 +lon_0=114 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs";
    proj4.defs("EPSG:4547", epsg4547Def);
    // 示例坐标 WGS84
    const wgs84Coord = [Number(x), Number(y)];
    // 执行转换
    let point4547trans = proj4("EPSG:4326", "EPSG:4547", wgs84Coord);
    const point4547 = new Point({
      x: point4547trans[0],
      y: point4547trans[1],
      spatialReference: { wkid: 4547 }, // EPSG:4547
    });

    view.goTo({
      target: point4547, // 使用几何的中心，如果没有extent则使用几何本身
      zoom: 15, // 调整缩放级别以适合您的需求
    });
  };

  const flyById = (targetId: any) => {
    let targetGraphic: any = null; // 用于存储找到的目标图形

    if (highGraphic) {
      const newSymbol = highGraphic.symbol.clone();
      newSymbol.width = "104px"; // 比如 "150px"
      newSymbol.height = "104px"; // 比如 "150px"
      highGraphic.symbol = newSymbol;
      console.log(highGraphic, "highGraphic2");
    }
    graphicsLayer.graphics.forEach((graphic: any) => {
      // 检查图形是否有 id 属性，并且该属性是否匹配您的目标 ID
      if (graphic.attributes && graphic.attributes.id === targetId) {
        targetGraphic = graphic;

        const newSymbol = graphic.symbol.clone();
        newSymbol.width = "150px"; // 比如 "150px"
        newSymbol.height = "150px"; // 比如 "150px"
        graphic.symbol = newSymbol;
      }
    });

    if (targetGraphic) {
      view.goTo(targetGraphic.geometry);
      highGraphic = targetGraphic;
    } else {
      console.log("未找到 ID 为 " + targetId + " 的图形");
    }
  };
  const controlByType = (type: string, show: Boolean) => {
    graphicsLayer.graphics.forEach((graphic: any) => {
      if (graphic.attributes && graphic.attributes.type === type) {
        graphic.visible = show;
      }
    });
  };
  const switchPart = (arr: Array<any>) => {
    // graphicsLayer.graphics.forEach((graphic: any) => {
    //   const isVisible = arr.some(
    //     (item) => item.text === graphic.attributes.type
    //   );
    //   graphic.visible = isVisible;
    // });
  };
  const controlSubwayVisible = () => {
    subWaylayer.visible = !subWaylayer.visible;
  };
  const controlPortgraphicsLayerVisible = () => {
    PortgraphicsLayer.visible = !PortgraphicsLayer.visible;
  };
  //调整透明度
  const changeOpacity = (node: any, value: any) => {
    let ob = (mapControlVisibleMap as any).get(node.data.id.toString());
    ob.opacity = value / 100;
    mapControOpacityMap.set(node.data.id.toString(), value);
  };
  //获取单独的透明度
  const getUniqueOpacity = (node: any) => {
    return mapControOpacityMap.get(node.data.id.toString());
  };
  const updateNodeValueById = (tree: any, id: any, newValue: any) => {
    // 遍历整个树
    for (let node of tree) {
      // 检查当前节点是否匹配目标 id
      if (node.id === id) {
        // 更新值
        node.value = newValue;
        return true; // 找到后返回 true
      }

      // 如果当前节点有 children，递归调用
      if (node.children && node.children.length > 0) {
        // 递归调用函数
        const found = updateNodeValueById(node.children, id, newValue);
        if (found) return true; // 如果在子节点中找到了，返回 true
      }

      // 如果当前节点有 value（表示是文件夹），递归调用
      if (node.value && Array.isArray(node.value)) {
        // 递归调用函数
        const found = updateNodeValueById(node.value, id, newValue);
        if (found) return true; // 如果在 value 中找到了，返回 true
      }
    }

    return false; // 如果没有找到，返回 false
  };
  const findGraphicById = (graphicId: any) => {
    console.log(view.graphics, "view.graphics");

    return view.graphics.filter(
      (graphic: any) =>
        graphic.attributes && graphic.attributes.id === graphicId
    );
  };

  const findGraphicBybh = (graphicId: any) => {
    let foundGraphics
    graphicsLayersList.forEach((layer:any)=>{
      layer.graphics.filter((graphic:any)=>{
        console.log(graphic.attributes.sbbh, graphicId, "findGraphicBybh");
        if(graphic.attributes.sbbh === graphicId){
          foundGraphics=graphic
        }
      });
  }
     )
    console.log(foundGraphics, "foundGraphics");
    
     return  foundGraphics
  }
  const getIndicatorDataInt = async (id: any) => {
    let res = await API.common.getIndicator({
      id: id,
    });
    return res.data.data.map((item: any) => {
      return {
        name: item.name,
        value: Math.round(Number(item.value)),
      };
    });
    console.log(res, "getIndicatorData");
  };

  const setDefaultOption = (echarts: any) => {
    echarts.setOption({
      tooltip: {
        backgroundColor: "rgba(28,64,81,0.7)",
        textStyle: {
          color: "white",
          fontSize: 20,
        },
      },
      yAxis: [
        {
          axisLabel: {
            fontSize: 20,
            interval: 0,
            fontFamily: "OPPOSans-Regular",
            color: "#667A8E",
          },
          nameTextStyle: {
            color: "#DEDEDE",
            fontSize: 20,
            fontFamily: "OPPOSans-Regular",
          },
        },
      ],
      xAxis: {
        axisLabel: {
          fontSize: 20,
          interval: 0,
          fontFamily: "OPPOSans-Regular",
          color: "#667A8E",
        },
        nameTextStyle: {
          color: "#DEDEDE",
          fontSize: 20,
          fontFamily: "OPPOSans-Regular",
        },
      },
    });
  };
  const getData=async(firstKey:any,secondKey:any)=>{
  const apiUrl = import.meta.env.VITE_SERVER_URL;
  const axiosInstance = axios.create({
    baseURL: apiUrl,
  });

  try {
    const response = await axiosInstance.get('/chart/getChartData', {
      params: {
        firstKey: firstKey,
        secondKey: secondKey
      }
    });

    // 等待 response.data.data 的 Promise 解析
    const data = await response.data.data;
    // const data = await Promise.resolve(response.data.data);
    console.log(data, "GLpoint");
    
    return  JSON.parse(JSON.stringify(data)); // 现在 data 是一个 JSON 对象
  } catch (error) {
    console.error("Error fetching data:", error);
    throw error;
  }
  
  }
  const getallData=async()=>{
    const apiUrl = import.meta.env.VITE_SERVER_URL;
    const axiosInstance = axios.create({
      baseURL: apiUrl,
    });
  
    try {
      const response = await axiosInstance.get('/chart/getChartData', {
        params: {
        }
      });
  
      // 等待 response.data.data 的 Promise 解析
      const data = await response.data.data;
      // const data = await Promise.resolve(response.data.data);
      console.log(data, "GLpoint");
      
      return  JSON.parse(JSON.stringify(data)); // 现在 data 是一个 JSON 对象
    } catch (error) {
      console.error("Error fetching data:", error);
      throw error;
    }
    
    }
  return {
    createMap,
    getDataTreeDataByTitle,
    changeVisible,
    addpoint,
    autoScroll,
    underGroundScenceList,
    scenceList,
    flyById,
    controlSubwayVisible,
    controlPortgraphicsLayerVisible,
    controlByType,
    switchPart,
    getIndicatorDataInt,
    setDefaultOption,
    locationByid,
    changeOpacity,
    getUniqueOpacity,
    flyByXY,
    tabClick,
    jumpDetail,
    getGLData,
    flyByXY4326,
    showPopUpGl,
    getData,
    getallData,
  };
}
